<template>
    <div>
        <div class="info-wrapper">
            <van-field type="digit" class="label-class" :error-message="phoneError" v-model="phone" @input="inputPhone"
                label="联系方式(必填)" placeholder="手机号" />
            <div class="upload-wrapper">
                <div class="upload-title">
                    <span style="font-size: 16px;">图片证据(选填)</span>
                    <span>{{ fileList.length }}/9</span>
                </div>
                <van-uploader v-model="fileList" :after-read="handleUpload" :before-delete="handleDelete" multiple
                    :max-count="9" />
            </div>
            <van-field v-model="remark" autosize label="" type="textarea" maxlength="200" placeholder="请输入留言"
                show-word-limit />

        </div>
        <div class="btn-wrapper">
            <van-button style="width:184px; background: #f2f2f2; height: 38px; font-weight: 500; font-size: 16px;"
                :disabled="!disableBtn" @click="handleSubmit" :type="disableBtn ? 'success' : 'default'">提交</van-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { showToast } from 'vant';
import { computed, ref } from 'vue';
import COS from 'cos-js-sdk-v5';
import { saveProcess } from '@/api/mock/index'
import validator from 'validator'
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const phone = ref('');
const fileList = ref([]);
const remark = ref('');
const cos = new COS({
    SecretId: 'AKIDZEtSn15xjLn271iEYhxGeDfysfa7Wiy4',
    SecretKey: '4bzGOQSM7f4KMAqKsSyJyRggSvHsRyaA',
})
const toastMessage = ref('');
const phoneError = ref('');

const disableBtn = computed(() => {
    return phone.value || fileList.value.length || remark.value
})

const inputPhone = () => {
    phoneError.value = ''
}
const handleSubmit = () => {
    if (!phone.value) {
        phoneError.value = '请输入手机号'
        return
    }
    if (!validator.isMobilePhone(phone.value)) {
        phoneError.value = '请输入正确的手机号'
        return
    }

    if (!fileList.value.length) {
        showToast("请上传图片");
        return
    }

    const imageKeys = fileList.value.map(item => `xiaoyi/image/${item.file.name}`)
    const params = {
        phone: phone.value,
        imageKey: imageKeys.join(','),
        content: remark.value,
        reasonId: route.query.id,
        reasonName: route.query.name,
        corpId: localStorage.getItem('appid'),
    }
    saveProcess({ ...params }).then((res: any) => {
        router.replace('/result')
        window.history.pushState(null, '', '/result');
    })
}

const uploadFunc = async (file) => {
    try {
        const res: any = await uploadToCOS(file.file);
        toastMessage.value = '上传成功！';
        console.log('文件地址:', res);
    } catch (error) {
        console.log('上传失败:', error);
        toastMessage.value = '上传失败: ' + error.message;
    }
}
const handleUpload = async (file: any) => {
    if (Array.isArray(file)) {
        file.forEach(async element => {
            await uploadFunc(element)
        });
    } else {
        await uploadFunc(file)
    }
};

const uploadToCOS = (file) => {
    return new Promise((resolve, reject) => {
        cos.putObject(
            {
                Bucket: 'welkin-1326777323',
                Region: 'ap-beijing',
                Key: `xiaoyi/image/${file.name}`,
                Body: file,
                onProgress: (progressData) => {
                    console.log('上传进度:', progressData);
                },
            },
            (err, data) => {
                if (err) reject(err);
                else resolve(data);
            }
        );
    });
}

const handleDelete = (item) => {
    // 可选：调用 COS SDK 删除已上传文件
    return true; // 返回 true 允许删除
}
</script>

<style lang="less" scoped>
.info-wrapper {
    padding: 16px;
    background: #fff;

    .label-class {

        :deep(.van-field__label) {
            width: 110px !important;
            font-size: 16px !important;
        }
    }

    :deep(.van-field__control) {
        font-size: 16px;
    }

    .phone-validate {
        color: red;
        border: 1px solid red;
        margin: 10px 16px;
        border-radius: 4px;
        padding: 8px;
    }

    .upload-wrapper {
        padding: 10px 16px;

        .upload-title {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
        }
    }
}

.btn-wrapper {
    margin-top: 46px;
    display: flex;
    justify-content: center;

    :deep(.van-button--success) {
        background: #07c160 !important;
    }
}
</style>